package com.wusuowei.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wusuowei.auth.model.dto.UserExt;
import com.wusuowei.auth.model.vo.AuthParamsVo;
import com.wusuowei.auth.service.AuthService;
import com.wusuowei.checkcode.service.impl.PicCheckCodeServiceImpl;
import com.wusuowei.common.utils.RespEnum;
import com.wusuowei.config.exception.ServiceException;
import com.wusuowei.ucenter.mapper.SysUserMapper;
import com.wusuowei.ucenter.model.po.SysUser;
import com.wusuowei.ucenter.service.ISysRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @description 邮件认证
 * @author LGY
 * @date 2023/04/11 18:57
 * @version 1.0.0
 */
@Service("email_authservice")
public class EmailServiceImpl implements AuthService {


    @Autowired
    SysUserMapper sysUserMapper;


    @Autowired
    ISysRoleService roleService;

    @Autowired
    PicCheckCodeServiceImpl picCheckCodeService;

    @Override
    public UserExt execute(AuthParamsVo authParamsVo) {
        //得到验证码
        String checkcode = authParamsVo.getCheckcode();
        String emailkey = authParamsVo.getEmail();
        if(StringUtils.isBlank(emailkey) || StringUtils.isBlank(checkcode)){
            throw new ServiceException(RespEnum.CODE_IS_EMPTY);

        }
        //校验验证码,请求验证码服务进行校验
        Boolean result = picCheckCodeService.verify(emailkey, checkcode);
        if(result==null || !result){
            throw new ServiceException(RespEnum.CODE_ERROR);
        }

        //邮箱
        String email = authParamsVo.getEmail();
        //从数据库查询用户信息
        SysUser sysUser = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, email));
        if (sysUser == null) {
            throw new ServiceException(RespEnum.USER_NOT_EXISTS);
        }
        sysUser.setLoginTime(LocalDateTime.now());
        sysUserMapper.updateById(sysUser);
        sysUser.setRole(roleService.getRoles(String.valueOf(sysUser.getId())));
        UserExt userExt = new UserExt();
        BeanUtils.copyProperties(sysUser,userExt);
        return userExt;
    }

}
